{% extends 'layout/manage.html' %}
{% load static %}
{% block title %} {% endblock %}
{% block css %}
    <style>
        {#    将标题行改成分散布局    #}
        .panel-default .panel-heading {
            display: flex;
            flex-direction: row;
            justify-content: space-between;
        }

        .panel-default > .panel-heading a {
            text-decoration: none;
        }

        .panel-default > .panel-heading span {
            padding: 0 5px;
        }

        .panel-default > .panel-heading .function .upload {
            overflow: hidden;
        }

        .panel-default > .panel-heading .function .upload input {
            opacity: 0;
            position: absolute;
            top: 0;
            bottom: 0;
            width: 76px;
            left: -2px;
            overflow: hidden;

        }

        .upload-Progress {
            position: fixed;
            right: 2px;
            bottom: 2px;
            width: 450px;
        }

        .upload-Progress .progress-error {
            color: red;
        }

        table > thead > td {
            text-align: center;
        }

        #rowList > tr > td {
            text-align: center;
        }
    </style>

{% endblock %}


{% block content %}
    {#    <div class="alert alert-success" role="alert" id="error"></div>#}
    <div class="container-fluid">
        <div class="panel panel-default" style="margin-top: 20px">
            <!-- Default panel contents -->
            <div class="panel-heading">
                <div>
                    <a href="{% url 'web:file'  project_id=request.tracer.project.id %}">
                        <i class="fa fa-home" aria-hidden="true"></i>
                        <span>文件库</span>
                    </a>
                    {% for record in breadcrumb_list %}
                        <a href="{% url 'web:file'  project_id=request.tracer.project.id %}?folder={{ record.id }}">
                            <i class="fa fa-caret-right" aria-hidden="true"></i>
                            <span>{{ record.file_name }}</span>
                        </a>
                    {% endfor %}
                </div>
                <div class="function">
                    {#   上传文件按钮                 #}
                    <div class="btn btn-primary btn-xs upload" style="position: relative;">
                        <div><i class="fa fa-upload" aria-hidden="true"></i>上传文件</div>
                        <input type="file" multiple name="uploadFile" id="uploadFile" onChange="bindUploadFile(this)">

                    </div>

                    {#   新建文件夹按钮                 #}
                    <a type="button" class="btn btn-success btn-xs" data-toggle="modal"
                       data-target="#addFileModel" data-whatever="新建文件夹">
                        <i class="fa fa-plus-circle" aria-hidden="true"></i> 新建文件夹
                    </a>
                </div>
            </div>


            <!-- 文件列表 -->
            <table class="table">
                <thead>
                <th style="text-align: center">文件名称</th>
                <th style="text-align: center">文件大小</th>
                <th style="text-align: center">创建者</th>
                <th style="text-align: center">创建时间</th>
                <th style="text-align: center">更新者</th>
                <th style="text-align: center">更新时间</th>
                <th style="text-align: center">操作</th>
                </thead>
                <tbody id="rowList">
                {% for item in file_object_list %}
                    <tr>
                        <td style="text-align: left">
                            {% if item.file_type == 2 %}
                                <i class="fa fa-folder" aria-hidden="true" style="color: #337ab7"></i>
                            {% else %}
                                <i class="fa fa-file" aria-hidden="true" style="color: green"></i>
                            {% endif %}
                            <a href="{% url 'web:file'  project_id=request.tracer.project.id %}?folder={{ item.id }}">
                                {{ item.file_name }}
                            </a>
                        </td>
                        <td style="text-align: center; width: 10%">
                            {% if item.file_type == 1 %}
                                {% if  1024 > item.file_size %}
                                    {{ item.file_size }}B
                                {% else %}
                                    {% if 1048576 > item.file_size %}
                                        {% widthratio item.file_size 1024 1 %}KB
                                    {% else %}
                                        {% if 1073741824 > item.file_size %}
                                            {% widthratio item.file_size 1048576 1 %}MB
                                        {% else %}
                                            {% widthratio item.file_size 1073741824 1 %}GB
                                        {% endif %}
                                    {% endif %}
                                {% endif %}
                            {% else %}
                                -
                            {% endif %}
                        </td>
                        <td style="text-align: center; width: 10%">{{ item.create_user.username }}</td>
                        <td style="text-align: center; width: 15%">{{ item.create_datetime|date:'Y年-m月-d日 H:m' }}</td>
                        <td style="text-align: center; width: 10%">{{ item.update_user.username }}</td>
                        <td style="text-align: center; width: 15%">{{ item.update_datetime|date:'Y年-m月-d日 H:m' }}</td>
                        <td style="text-align: left; width: 10%">
                            {#        修改文件夹                #}
                            {% if item.file_type == 2 %}
                                <a class="btn btn-success btn-xs"
                                   data-toggle="modal"
                                   data-target="#addFileModel"
                                   data-whatever="编辑文件夹"
                                   data-name="{{ item.file_name }}"
                                   data-fid="{{ item.id }}">
                                    <i class="fa fa-pencil-square-o"></i>
                                </a>
                            {#        下载文件                #}
                            {% else %}
                                <a class="btn btn-danger btn-xs download" style="background-color: red"
                                   href="{% url 'web:download_file' project_id=request.tracer.project.id file_id=item.id%}">
                                    <i class="fa fa-cloud-download" aria-hidden="true"></i>
                                </a>
                            {% endif %}
                            <a class="btn btn-danger btn-xs" style="background-color: red"
                               data-toggle="modal"
                               data-target="#deleteModel"
                               data-whatever="删除文件或文件夹"
                               data-fid="{{ item.id }}">
                                <i class="fa fa-trash" aria-hidden="true"></i>
                            </a>
                        </td>


                    </tr>
                {% endfor %}
                </tbody>
            </table>
        </div>
    </div>

    <!-- 新建文件夹模态框 -->
    <div class="modal fade" id="addFileModel" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true"></span>
                    </button>
                    <h4 class="modal-title" id="myModalLabel" style="font-weight: 700"></h4>
                </div>
                <div class="modal-body">
                    <form id="form">
                        {% csrf_token %}
                        <input class="hide" name="fid" id="fid">
                        {% for field in form %}
                            <div class="form-group">
                                <label for="{{ field.id_for_label }}">{{ field.label }}</label>
                                <div>
                                    {{ field }}
                                    <span class="error-msg">{{ field.errors.0 }}</span>
                                </div>

                            </div>
                        {% endfor %}
                    </form>

                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">取 消</button>
                    <button id="btnFormSubmit" type="button" class="btn btn-primary">确 定</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 删除文件夹模态框 -->
    <div class="modal fade" id="deleteModel" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="alert alert-danger alert-dismissible fade in" role="alert">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                        aria-hidden="true">×</span></button>
                <h4>是否确定删除？</h4>
                <p style="padding-top: 20px;padding-bottom: 20px;">
                    文件夹中包含的所有文件都会被删除！！！
                </p>
                <p style="text-align: right">
                    <a class="btn btn-default btn-sm" data-dismiss="modal" aria-label="Close">取 消</a>
                    <button id="btnDelete" type="button" class="btn btn-danger btn-sm">确 定</button>
                </p>
            </div>
        </div>
    </div>

    <!-- 显示文件上传进度条 -->
    <div id="uploadProgress" class="upload-Progress hide">
        <div class="panel panel-primary">
            <div class="panel-heading"><i class="fa fa-cloud-upload" aria-hidden="true"></i>上传进度</div>
            <table class="table">
                <tbody id="progressList">
                <!-- 这里显示文件上传的进度条，由js控制 -->
                </tbody>
            </table>
        </div>

    </div>

    <!-- 文件上传进度条模板，每上传一个文件就克隆一份 -->
    <div class="hide">
        <table id="progressTemplate">
            <tr>
                <td>
                    <div class="name"></div>
                    <div class="size"></div>
                    <div class="progress">
                        <div class="progress-bar progress-bar-success progress-bar-striped"
                             role="progressbar"
                             aria-valuenow="0"
                             aria-valuemin="0"
                             aria-valuemax="100"
                             style="width: 0;">
                            0%
                        </div>
                    </div>
                    <div class="progress-error"></div>

                </td>
            </tr>
        </table>
    </div>

    <!-- 上传文件后，自动在文件列表加一条文件记录模板 -->
    <div class="hide">
        <table id="rowTemplate">
            <tr>
                <td style="text-align: left">
                    <i class="fa fa-file" aria-hidden="true" style="color: green"></i>
                    <span class="file_name"></span>
                </td>
                <td class="file_size" style="text-align: center; width: 10%"></td>
                <td class="create_user" style="text-align: center; width: 10%"></td>
                <td class="create_datetime" style="text-align: center; width: 15%"></td>
                <td class="update_user" style="text-align: center; width: 10%"></td>
                <td class="update_datetime" style="text-align: center; width: 15%"></td>
                <td style="text-align: left; width: 10%">
                    <!-- 下载文件按钮 -->
                    <a class="btn btn-danger btn-xs download" style="background-color: red">
                        <i class="fa fa-cloud-download" aria-hidden="true" href=""></i>
                    </a>
                    <!-- 删除文件按钮 -->
                    <a class="btn btn-danger btn-xs delete" data-toggle="modal" data-target="#deleteModel"
                       style="background-color: red">
                        <i class="fa fa-trash" aria-hidden="true"></i>
                    </a>
                </td>
            </tr>
        </table>
    </div>

{% endblock %}



{% block js %}
    <script src="{% static 'js/cos-js-sdk-v5.min.js' %}"></script>
    <script>
        const FOLDER_URL = "{% url 'web:file' project_id=request.tracer.project.id %}";
        const FOLDER_DELETE_URL = "{% url 'web:file_delete' project_id=request.tracer.project.id%}";
        const COS_CREDENTIAL = "{% url 'web:cos_credential' project_id=request.tracer.project.id%}";
        const SAVE_FILE_TO_DATABASE = "{% url 'web:save_database' project_id=request.tracer.project.id%}";
        const CURRENT_FOLDER_ID = "{{ folder_object.id }}";


        $(function () {
            initAddFile();  // 初始化模态框
            bindFormSubmit();  // 新增文件夹模态框确定按钮绑定事件
            bindDeleteSubmit();  // 删除文件夹模态框确定按钮绑定事件

        });

        /**
         * 上传文件
         */
        function bindUploadFile(that) {
            $('#progressList').empty();
            const fileList = $(that)[0].files;
            const checkFileList = []
            $.each(fileList, function (index, fileObject) {
                checkFileList.push({'name': fileObject.name, 'size': fileObject.size})
            });

            // 把这些数据发送到django后台：Django后台进行容量的校验，如果没问题则返回临时凭证；否则返回错误信息；
            const COS_OBJECT = new COS({
                getAuthorization: function (options, callback) {
                    $.post(COS_CREDENTIAL, JSON.stringify(checkFileList), function (res) {
                        if (res.status) {
                            const credentials = res.data && res.data.credentials;
                            callback({
                                TmpSecretId: credentials.tmpSecretId,
                                TmpSecretKey: credentials.tmpSecretKey,
                                XCosSecurityToken: credentials.sessionToken,
                                StartTime: res.data.startTime,
                                ExpiredTime: res.data.expiredTime
                            });
                            $('#uploadProgress').removeClass('hide');
                            console.log(2);
                        } else {
                            alert(res.error);
                        }
                    });
                }
            });

            $.each(fileList, function (index, fileObject) {
                console.log(3);
                const fileName = fileObject.name;
                const fileSize = fileObject.size;
                const key_name = (new Date()).getTime() + "_" + fileName;

                const tr = $("#progressTemplate").find('tr').clone(true);
                tr.find(".name").text('文件名称：' + fileName);
                tr.find(".size").text('文件大小：' + parseInt(fileSize / 1024) + 'KB');
                $("#progressList").append(tr);
                // 上传文件(异步)
                COS_OBJECT.putObject({
                    Bucket: '{{ request.tracer.project.bucket }}',
                    Region: '{{ request.tracer.project.region }}',
                    Key: key_name,
                    StorageClass: 'STANDARD',
                    Body: fileObject,
                    onProgress: function (progressData) {
                        {#console.log("文件上传进度---->", fileObject.name, JSON.stringify(progressData));#}
                        const percent = progressData.percent * 100 + "%";
                        tr.find(".progress-bar").text(percent);
                        tr.find(".progress-bar").css("width", percent);
                    }
                }, function (err, data) {
                    console.log(err || data)
                    if (data && data.statusCode === 200) {
                        // 如果上传成功，将本次上传的文件记录保存到数据库
                        const file_info = {
                            "file_name": fileName,
                            "file_size": fileSize,
                            "key_name": key_name,
                            "file_path": data.Location,
                            "parent": CURRENT_FOLDER_ID,
                            "ETag": data.ETag
                        }
                        $.post(SAVE_FILE_TO_DATABASE, file_info, function (res) {

                            let file_size = res.data.file_size
                            if (file_size < 1024) {
                                file_size = file_size + "B"
                            } else {
                                if (file_size < (1024 * 1024)) {
                                    file_size = Math.floor(file_size / 1024) + "KB"
                                } else {
                                    if (file_size < (1024 * 1024 * 1024)) {
                                        file_size = Math.floor(file_size / 1024 / 1024) + "MB"
                                    } else {
                                        file_size = Math.floor(file_size / 1024 / 1024 / 1024) + "GB"
                                    }
                                }
                            }

                            const new_tr = $("#rowTemplate").find('tr').clone();
                            new_tr.find(".file_name").text(res.data.file_name);
                            new_tr.find(".file_size").text(file_size);
                            new_tr.find(".create_user").text(res.data.create_user);
                            new_tr.find(".create_datetime").text(res.data.create_datetime);
                            console.log(res.data.create_datetime)
                            new_tr.find(".update_user").text(res.data.update_user);
                            new_tr.find(".update_datetime").text(res.data.update_datetime);
                            new_tr.find(".delete").attr("data-fid", res.data.file_id);
                            <!--为下载按钮添加href属性，点击下载文件 -->
                            new_tr.find(".download").attr("href", res.data.download_url);
                            <!-- 将创建的文件tr标签添加到 文件列表中-->
                            $("#rowList").append(new_tr);

                            {#location.href = location.href#}
                            setTimeout(function () {
                                tr.remove();
                                $("#uploadProgress").addClass("hide");
                            }, 1000);
                        });

                    } else {
                        tr.find(".progress-error").text("上传失败")
                    }

                });
            });

        }

        /**
         * 删除文件夹、文件
         */
        function bindDeleteSubmit() {
            $("#btnDelete").click(function () {
                // 获取要删除文件夹的id
                $.ajax({
                    url: FOLDER_DELETE_URL,
                    type: "GET",
                    data: {fid: $(this).attr("fid")},
                    success: function (res) {
                        if (res.status) {
                            location.href = location.href
                        } else {
                            alert("出了点问题！！！")
                        }

                    }

                })
            })

        };

        /**
         * 初始化模态框内容
         */
        function initAddFile() {
            $('#addFileModel').on('show.bs.modal', function (event) {
                const button = $(event.relatedTarget); // Button that triggered the modal
                const recipient = button.data('whatever');
                // Extract info from data-* attributes
                // If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
                // Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
                const fid = button.data('fid');
                const name = button.data('name');

                const modal = $(this);
                modal.find('.modal-title').text(recipient)
                {#modal.find('.modal-body input').val(recipient)#}
                if (fid) {
                    // 修改文件夹
                    // 将文件夹名称写入文本框
                    modal.find("#id_file_name").val(name);
                    modal.find("#fid").val(fid);
                } else {
                    // 新建文件夹
                    modal.find('.error-msg').empty();
                    $('#form')[0].reset();
                }
            });

            $('#deleteModel').on('show.bs.modal', function (event) {
                const button = $(event.relatedTarget); // Button that triggered the modal
                const fid = button.data('fid');
                $("#btnDelete").attr("fid", fid);
            });
        };

        /**
         * 新增文件夹表单异步提交
         */
        function bindFormSubmit() {
            $('#btnFormSubmit').click(function () {
                $.ajax({
                    url: location.href,
                    type: "POST",
                    data: $("#form").serialize(),
                    dataType: "JSON",
                    success: function (res) {
                        if (res.status) {
                            location.href = location.href;
                        } else {
                            $.each(res.error, function (key, value) {
                                $("#id_" + key).next().text(value[0]);
                            })
                        }
                    }
                })
            })
        };


    </script>

{% endblock %}